SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


alter    procedure p_updatemnfworkingacceptqty
  @relationbid integer,
  @relationbno integer,
  @bdate datetime,
  @diffqty decimal(18,4)
as
declare @manuqty decimal(18,4), 
        @unitmanhour decimal(18,4)

  if exists(select m.bid from tb_mnfmaking m
    left join tb_mnfmakingdtl d on m.bid=d.bid 
    where  d.relationbid=@relationbid 
      and year(m.bdate)>=year(@bdate) and month(m.bdate)>=month(@bdate)) 
  begin
    select  @manuqty=quantity,@unitmanhour=manhour/quantity from tb_mnfmachiningdtl where bid=@relationbid and bno=@relationbno
    update tb_mnfmakingdtl set completedqty = completedqty+ @diffqty,
	bquantity = case when (@manuqty-(completedqty+@diffqty))*rate>0 then (@manuqty-(completedqty+@diffqty))*rate
	else 0 end,
	quantity = case when (@manuqty-(completedqty+@diffqty))*rate>0 then (@manuqty-(completedqty+@diffqty))*rate
	else 0 end,	 		
	unit1qty = case when (@manuqty-(completedqty+@diffqty))*rate>0 then (@manuqty-(completedqty+@diffqty))*rate
	else 0 end,
	manhour = @unitmanhour*(case when (@manuqty-(completedqty+@diffqty))*rate>0 then (@manuqty-(completedqty+@diffqty))*rate
	else 0 end)	 		
      where relationbid =@relationbid 
	and bid in (select m.bid from tb_mnfmaking m
	left join tb_mnfmakingdtl d on(m.bid=d.bid)
	where  d.relationbid=@relationbid and d.relationbno=@relationbno
	and year(m.bdate)>=year(@bdate) and month(m.bdate)>=month(@bdate)) 
end


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

